"""
V2 
多线程队列
按顺序执行命令
固定命令行
"""
import pygame
import vgamepad as vg
import time
import threading
from queue import Queue

# 命令映射
command_map = {
    'w': ('left', 0.0, 1.0, "左摇杆向上移动"),
    's': ('left', 0.0, -1.0, "左摇杆向下移动"),
    'a': ('left', -1.0, 0.0, "左摇杆向左移动"),
    'd': ('left', 1.0, 0.0, "左摇杆向右移动"),
    '上': ('right', 0.0, 1.0, "右摇杆向上移动"),
    '下': ('right', 0.0, -1.0, "右摇杆向下移动"),
    '左': ('right', -1.0, 0.0, "右摇杆向左移动"),
    '右': ('right', 1.0, 0.0, "右摇杆向右移动"),
    'A': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_A, "A按钮"),
    'B': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_B, "B按钮"),
    'X': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_X, "X按钮"),
    'Y': ('button', vg.XUSB_BUTTON.XUSB_GAMEPAD_Y, "Y按钮"),
    '空': ('empty')
}

class GamepadController:
    def __init__(self):
        self.gamepad = vg.VX360Gamepad()
        self.command_queue = Queue()
        self.running = True
        print("虚拟手柄创建成功")
    
    def left_thread_worker(self, command_string):
        """左摇杆和按钮线程"""
        for char in command_string:
            if char in ['w', 'a', 's', 'd', 'A', 'B', 'X', 'Y']:
                self.command_queue.put(char)
                time.sleep(0.1)  # 命令间间隔
    
    def right_thread_worker(self, command_string):
        """右摇杆线程"""
        for char in command_string:
            if char in ['上', '下', '左', '右']:
                self.command_queue.put(char)
                time.sleep(0.1)  # 命令间间隔
    
    def process_commands(self):
        """处理命令队列"""
        while self.running or not self.command_queue.empty():
            try:
                char = self.command_queue.get(timeout=0.1)
                if char in command_map:
                    command = command_map[char]
                    print(f"执行命令: {char} - {command[-1]}")
                    
                    if command[0] == 'left':  # 左摇杆命令
                        _, x_axis, y_axis, _ = command
                        self.gamepad.left_joystick_float(x_value_float=x_axis, y_value_float=y_axis)
                        self.gamepad.update()
                        print(f"左摇杆移动到: X={x_axis}, Y={y_axis}")
                        time.sleep(1)
                        
                        # 重置摇杆
                        self.gamepad.left_joystick_float(x_value_float=0.0, y_value_float=0.0)
                        self.gamepad.update()
                        print("左摇杆回中")
                    
                    elif command[0] == 'right':  # 右摇杆命令
                        _, x_axis, y_axis, _ = command
                        self.gamepad.right_joystick_float(x_value_float=x_axis, y_value_float=y_axis)
                        self.gamepad.update()
                        print(f"右摇杆移动到: X={x_axis}, Y={y_axis}")
                        time.sleep(1)
                        
                        # 重置摇杆
                        self.gamepad.right_joystick_float(x_value_float=0.0, y_value_float=0.0)
                        self.gamepad.update()
                        print("右摇杆回中")
                        
                    elif command[0] == 'button':  # 按钮命令
                        _, button, _ = command
                        self.gamepad.press_button(button=button)
                        self.gamepad.update()
                        print(f"按下按钮: {button}")
                        time.sleep(1)
                        
                        self.gamepad.release_button(button=button)
                        self.gamepad.update()
                        print(f"释放按钮: {button}")
                        time.sleep(0.1)
                        
                    
                    time.sleep(0.1)
                
                self.command_queue.task_done()
                
            except:
                continue
    
    def execute_concurrent_sequence(self, left_commands, right_commands):
        """同时执行左右线程的命令序列"""
        print(f"开始执行命令序列 - 左线程: {left_commands}, 右线程: {right_commands}")
        
        # 创建处理线程
        processor_thread = threading.Thread(target=self.process_commands)
        processor_thread.daemon = True
        processor_thread.start()
        
        # 创建左右线程
        left_thread = threading.Thread(target=self.left_thread_worker, args=(left_commands,))
        right_thread = threading.Thread(target=self.right_thread_worker, args=(right_commands,))
        
        # 启动线程
        left_thread.start()
        right_thread.start()
        
        # 等待线程完成
        left_thread.join()
        right_thread.join()
        
        # 等待队列处理完成
        self.command_queue.join()
        
        # 停止处理线程
        self.running = False
        processor_thread.join(timeout=1.0)
        
        # 清理
        self.gamepad.reset()
        self.gamepad.update()
        print("命令序列执行完成")

def execute_command_sequence(command_string):
    """原有的顺序执行方式（兼容性保留）"""
    controller = GamepadController()
    
    # 分离左右命令
    left_commands = ''.join([c for c in command_string if c in ['w', 'a', 's', 'd', 'A', 'B', 'X', 'Y']])
    right_commands = ''.join([c for c in command_string if c in ['上', '下', '左', '右']])
    
    controller.execute_concurrent_sequence(left_commands, right_commands)

if __name__ == "__main__":
    time.sleep(5)
    
    # 示例1: 同时控制左右摇杆
    left_sequence = "wswsAwwssad"  # 左摇杆和按钮
    right_sequence = "左左左左左左左左左左左左左左左"  # 右摇杆
    
    controller = GamepadController()
    controller.execute_concurrent_sequence(left_sequence, right_sequence)
    
    # 示例2: 使用原有的字符串格式（自动分离）
    # time.sleep(2)
    # command_sequence = "A左A上上下下B右"
    # execute_command_sequence(command_sequence)